package com.itheima.demo2reflet;

import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class RefletDemo2
{
    @Test
    public void getConstructor () throws Exception {
        //拿类的构造器
        Class c1=Student.class;
        //获取构造器对象 拿数组接收
        Constructor[] cs=c1.getDeclaredConstructors();
        for (Constructor c:cs) {
            System.out.println(c);
        }
        //获取无参构造器
        Constructor c2=c1.getDeclaredConstructor();
        System.out.println(c2);
        //获取有参构造器
        Constructor c3=c1.getDeclaredConstructor(String.class,int.class);
        System.out.println(c3);
        //获取构造器的作用是创建对象
        //暴力反射 忽略访问权限修饰符
        c3.setAccessible(true);
        Student s= (Student) c3.newInstance("张三",18);
        System.out.println(s);
    }
    //获取成员变量
    @Test
    public void testGetField() throws Exception {
        Class c1=Student.class;
        Field f1=c1.getDeclaredField("name");
        System.out.println(f1);
        Field f2=c1.getDeclaredField("age");
        System.out.println(f2);
        Field f3=c1.getDeclaredField("sex");
        System.out.println(f3);
        //获取成员变量的目的是赋值
        f3.setAccessible(true);
        Student s=new Student("张三",18);
        f3.set(s,"男");
        System.out.println(s);
    }
    //获取成员方法
    @Test
    public void testGetMethod() throws Exception {
        Class c1=Student.class;
        Method m1=c1.getDeclaredMethod("study");
        Method m2=c1.getDeclaredMethod("study2", String.class);
        //获取成员方法的目的是调用
        Student s=new Student("张三",18);
        //唤醒方法
        m1.invoke(s);
        m2.invoke(s,"张三");
        Object o = m2.invoke(s, "李四");
        System.out.println(o);
    }
}
